<!--
 * @Description: 
 * @Version: 2.0
 * @Author: , // 文件作者
 * @Date: 2023-07-10 18:04:36
 * @LastEditors: 刘金开 liujinkai@jiankeyan.com
 * @LastEditTime: 2023-08-07 11:48:33
-->
<template>
  
 <el-card  class="boxCard" :body-style="{ padding: '10px 10px 5px' }"  >
  <div class="title" >
     <div class="mt-4" style=" display: inline-block;">
       <el-input v-model="input3" placeholder="请输入专业名称查询" clearable="true" class="input-with-select" style="width: 500px;  "  :prefix-icon="Search"
                 size="large">
                
         <!-- <template #prepend>
           <el-select v-model="select" placeholder="Select" size="large"  style="width: 120px">
          
             <el-option v-for="(item, index) in list" :key="index" :label="item.label" :value="item.value"></el-option>
           </el-select>
         </template> -->
         <template #append>
           <el-button  type="primary" text @click="searchFor"> 
            <el-icon><Search /></el-icon>
          </el-button>
           <!-- <el-button class="button" size="large" text >Operation button</el-button> -->
         </template>
       </el-input>
     </div>
     <div style=" display: inline-block;">
       <!-- <el-button type="primary" class="button"  size="large" text @click="getSpecialList">全部</el-button> -->
      
       <el-button text type="primary" size="large" @click="addSpecialClick">新增专业</el-button>
       
       <el-button text type="primary" size="large" @click="manyDelClick(arr)">批量删除</el-button>
        
       <el-button  class="iconBox" type="primary" text @click="getSpecialList">
        <el-icon class="hoverIcon"><RefreshRight /></el-icon>
        </el-button>
        <el-button text type="primary" size="large" @click="exportDownloadClick">导出下载</el-button>
      </div>
   </div>
  <!-- 表格 -->
  <div >
    <el-table
    id="tableId"
    border="true"
  :data="dataList"
  style="width: 100%;"
  max-height="554px"
 :highlight-current-row="true"
 :row-style="{height: '30px'}"
  @selection-change="selectionChange"
 >
  <el-table-column type="selection" width="35" />
  <el-table-column type="index" width="50"  align="center" />
  <el-table-column fixed prop="id" label="序号" width="20" v-if="false" />
    <el-table-column prop="name" label="专业名称" width="100"  align="center" :show-overflow-tooltip="true" />
    <el-table-column prop="created_at" label="创建时间"  align="center" width="120" />
    <el-table-column prop="updated_at" label="更新时间"  align="center" width="140" />
    <el-table-column prop="enable" header-align="center"  label="正在开设"   align="center" width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enable === false">否</el-tag>
            <el-tag type="success" v-else-if="scope.row.enable === true">是</el-tag>
          </template>
        </el-table-column>
	

    <el-table-column prop="note" label="备注" width="639"   align="center" :show-overflow-tooltip="true"/>
    <el-table-column fixed="right" label="操作" width="120"  align="center">
      <template   #default="scope">
        <el-button link type="primary" size="small" @click="editClick(scope)"
          >编辑</el-button
        >
        <el-button link type="danger" size="small" @click="handleDelete(scope.$index,scope)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
  </div>
 
  
    <!-- el-dialog 新增-->
  <el-dialog 
  v-model="showAddPage" 
  title="新增专业" 
  :modal="false"
  width="60%" 
   center>

   <el-form
   ref="ruleForms"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    :size="formSize"
    status-icon
  >
    <el-form-item label="专业名称"  prop="name" >
      <el-input v-model="ruleForm.name"  placeholder="请输入专业名称 " style="width: 200px;"/>
    </el-form-item>

    <el-form-item label="正在开设" prop="resource">
      <el-radio-group v-model="ruleForm.enable">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注"  prop="note" >
      <el-input v-model="ruleForm.note"  placeholder="" style="width: 550px;" />
    </el-form-item>
 
    <el-row type="flex" justify="center">
    <el-form-item  >
    
      <el-col :span="24">
        <el-button @click="showAddPage=false">取消</el-button>
      <el-button type="primary" @click="submitForm()">
        确认
      </el-button>
      </el-col>
    
    </el-form-item>
  </el-row>
  </el-form>

  

  </el-dialog>


<!-- 编辑 -->
<el-dialog 
  v-model="showEditPage" 
  title="编辑专业" 
  :modal="false"
  width="60%" 
   center>

   <el-form
    ref="ruleForms"
    :model="editForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    :size="formSize"
    status-icon
  >
    <el-form-item label="专业名称"  prop="name" >
      <el-input v-model="editForm.name"  placeholder="请输入专业名称 " style="width: 200px;"/>
    </el-form-item>

    <el-form-item label="正在开设" prop="resource">
      <el-radio-group v-model="editForm.enable">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注"  prop="note" >
      <el-input v-model="editForm.note"  placeholder="" style="width: 550px;" />
    </el-form-item>
 
     
    <el-row type="flex" justify="center">
    <el-form-item >
      <el-button @click="showEditPage=false">取消</el-button>
      <el-button type="primary" @click="submitEditForm()">
        确认
      </el-button>
    </el-form-item>
    </el-row>
  </el-form>

  

  </el-dialog>


  <div class="pageNation">
    <pagination  
     :pageSize="pageResult.pageSize"
   :layout="layout"
   :pageTotal="allPages"
    @pageFunc="pageFunc">
  </pagination>
</div>
 </el-card>
 
 </template>

<script  setup>
import {
    Message,
    Setting,
    Document,
    Memo,
    Reading,
    Star,
    User,
    Postcard,
    School,
    List,
    ElementPlus,
    Flag,
    Ticket,
    Platform,
    Expand, Fold,
    Search,
    RefreshRight
} from '@element-plus/icons-vue';
        import {getSpecialAll,addSpecial,editSpecial,deleteSpecial,getSpecialOne} from "../services/api/speciality.js";
        import {onMounted, reactive, ref, toRaw,nextTick ,watch,onBeforeMount ,toRefs } from "vue";
        import { ElNotification } from 'element-plus'
        import pagination from '../components/pageNation.vue'
        import{ exportDownload}from '../utils/exportExcel'
        const dataList = ref([]);
        const arr = ref([]);
        const input3=ref('');
        const showAddPage=ref(false);
        const showEditPage=ref(false);
        const manyDelList=ref([])
        const formSize = ref('default')
        const ruleForms = ref(null);  
        const arrs =ref([])
        const allPages=ref()
        const editForm=reactive({
          id:'',
          name: '',
          enable: false,
          note: '',
        })
        const ruleForm = reactive({
          name: '',
          enable: false,
          note: '',
        })

        const rules = reactive({
          name: [
            { required: true, message: '请输入专业名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度2到10个字符', trigger: 'blur' },
          ],

          enable: [
            {
              required: true,
              message: 'Please pick a time',
              trigger: 'change',
            },
          ],
          note: [
            {
              message: 'Please select activity resource',
              trigger: 'blur',
            },
          ],
        })
        let layout = "total,sizes, prev, pager, next,  ->,jumper, slot"; 
              const pageResult = reactive({
        // 放置页码及相关数据
        page: 1, //当前页
        pageSize: 20, //每页条目数
        
      });
 // 导出表格名称
const excelName=ref('专业信息')
      const pageFunc = (data) => {
        pageResult.pageSize = data.pageSize;
        pageResult.page = data.pageNum;
        getSpecialList();  // 触发获取数据函数
      };
      const getSpecialList = async () => {
        const res = await getSpecialAll(pageResult)
        dataList.value = res.data.data.specialities;
        allPages.value= res.data.data.count

      };
   
      const addSpecialClick = () => {
        showAddPage.value=true

      };

      // 编辑
      const editClick = (scope) => {
       showEditPage.value=true 
        // Object.assign(editForm,scope.row) 
        editForm.name= scope.row.name
        editForm.note= scope.row.note
        editForm.id= scope.row.id
        if(scope.row.enable==true){
          editForm.enable= true
        }else{
          editForm.enable= false
        }

      };
      // 编辑确定
      const submitEditForm=()=>{      
        editSpecial(editForm).then((res)=>{
          showEditPage.value=false
          if(res.data.msg=='OK'){
            getSpecialList()
            ElNotification({
                                    title: 'Success',
                                    message: '编辑专业成功',
                                    type: 'success',
                                      })
          }else{
            ElNotification({
                                      title: 'Error',
                                      message: '编辑专业失败',
                                      type: 'error',
                          })
          }
        })
        
       
      }

      // 查询
      const searchFor=()=>{
        let params={
          page:1,
          pageSize:5,
          name:input3.value,
        }
        getSpecialOne(params).then((res)=>{
          dataList.value = res.data.data.specialities;
          allPages.value= res.data.data.count;
        })

      }
      // 删除专业
      // const handleDelete = (index,scope) => {
      //  let id=scope.row.id
      //  let classname=scope.row.name
      //  arr.value=[]
      //   arr.value=[...arr.value,id]
      //   deleteSpecial(arr.value).then((res)=>{
      //       if(res.data.msg=='OK'){
      //        dataList.value.splice(index, 1)
      //        arr.value=[]
      //        ElNotification({
      //                               title: 'Success',
      //                               message: `成功删除--${classname}`,
      //                               type: 'success',
      //                                 })
      //       }else  if(res.data.msg=='数据存在被引用'){
      //       ElNotification({
      //                                 title: 'Error',
      //                                 message: `${classname}专业下有班级，不能删除`,
      //                                 type: 'error',
      //                     })
      //     }
           
      //   })
       
       
      
      // }
      const handleDelete = (index,scope) =>{
            ElMessageBox.confirm(
                `确认删除?  >>> ${scope.row.name}`,
                'Warning',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                  let id=scope.row.id
       let classname=scope.row.name
       arr.value=[]
        arr.value=[...arr.value,id]
        deleteSpecial(arr.value).then((res)=>{
            if(res.data.msg=='OK'){
             dataList.value.splice(index, 1)
             arr.value=[]
             ElNotification({
                                    title: 'Success',
                                    message: `成功删除--${classname}`,
                                    type: 'success',
                                      })
            }else  if(res.data.msg=='数据存在被引用'){
            ElNotification({
                                      title: 'Error',
                                      message: `${classname}专业下有班级，不能删除`,
                                      type: 'error',
                          })
          }
           
        })
                   
                    
                })
                .catch(() => {
                    ElNotification({
                        title: '撤销删除',
                        type: 'info',
                        message: 'deleted canceled',
                    })
                })
        }

      // 新增专业
      const submitForm= ()=>{
        ruleForms.value.validate((valid) => {
        if (valid) {
                  addSpecial(ruleForm).then((res)=>{
                    const { name } = toRefs(ruleForm); 
                              if(res.data.code === 200){
                                  showAddPage.value=false
                                  nextTick(() => {
                                      ruleForms.value.resetFields();
                                                  });
                                  ElNotification({
                                    title: 'Success',
                                    message: `成功新增--${name.value}专业`,
                                    type: 'success',
                                      })
                                      getSpecialList();
                        }else{
                                    ElNotification({
                                      title: 'Error',
                                      message: `新增--${name.value}专业失败`,
                                      type: 'error',
                          })
                        }
                  })

        }})
      
      }
 
    // 批量删除拿到id
      const selectionChange=(selection)=>{
                          arrs.value=[]
                let params = JSON.parse(JSON.stringify(selection));              
                        for( let i=0;i<params.length;i++ ){
                          arrs.value.push(params[i].id)
                        }
                        arr.value = [...new Set(arrs.value)];
                                        
      }
 
          //  批量删除
           const manyDelClick=(val)=>{
                   deleteSpecial(val).then((res)=>{
            if(res.data.msg=='OK'){
             getSpecialList( );
             arrs.value=[]
            }
           
        })
      }

// 导出下载
const exportDownloadClick=( ()=>{
  pageResult.pageSize = allPages.value;
  getSpecialAll(pageResult).then( async(res)=>{
  dataList.value = res.data.data.specialities;
  nextTick(() => {
    exportDownload(excelName.value,)
  });
})
})

 watch(input3, (newValue) => {
      if (newValue === '') {
        getSpecialList()
      }
    });

    watch(dataList, (newArr) => {
  newArr.forEach((obj) => {
    obj.created_at = obj.created_at.slice(0, 10);
    obj.updated_at = obj.updated_at.slice(0, 10);
  });
});



onMounted(()=>{
  getSpecialList();
})

</script>

<style scoped>
.title {
  height: 40px;
  padding: 5px 0;

}

.item {
  padding: 18px 0;
}


.table{
  position: relative;
}
 .boxCard {
  padding: 0;
    /* height: 100vh; */
}
.pageNation .pagination[data-v-b6487fcf]  {
padding: 0;
}

 .boxCard .el-card__body{
padding: 0;
}
.iconBox{
  position: fixed;
  right: 10px;
  
}


</style>
